package com.example.secondhand.controller;

import com.example.secondhand.common.enums.StatusEnum;
import com.example.secondhand.service.UserService;
import com.example.secondhand.common.enums.ErrorMsg;
import com.example.secondhand.model.shUser;
import com.example.secondhand.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.util.Random;

@CrossOrigin
@RestController//表明这个类是controller类
@RequestMapping("user")//此代码的映射路径前缀设置为/user
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 注册账号
     * @param userModel
     * @return
     * user 的status -1删除   ，0禁用，1启用
     */
    @PostMapping("sign-in")
    public ResultVo signIn(@RequestBody shUser userModel) {//请求体，前端请求后端的主题内容转换为java对象
        System.out.println(userModel);
        userModel.setSignInTime(new Timestamp(System.currentTimeMillis()));
        userModel.setUserStatus(StatusEnum.ENABL.getCode());//用户状态  -1删除，0禁用，1启用
        userModel.setUserAllow(StatusEnum.DISABLE.getCode());//管理员是否封号
        userModel.setSex(userModel.getSex());
        Random random = new Random();
        long randomNumber = (long)(random.nextDouble() * 1e16);
        userModel.setBank(String.valueOf(randomNumber));
        userModel.setLevel(5);
        userModel.setMoney(0D);//钱 双精度浮点数
        userModel.setScore(0D);
        userModel.setVouchers(0D);//券
        if (userModel.getAvatar() == null || "".equals(userModel.getAvatar())) {//头像
            userModel.setAvatar("/image?imageName=noasndo123.jpg");
        }
        if (userService.userSignIn(userModel)) {
            return ResultVo.success(userModel);
        }
        return ResultVo.fail(ErrorMsg.REGISTER_ERROR);
    }


    /**
     *
     *
     * @param accountNumber
     * @param userPassword
     * @param response
     * @return
     */
    @RequestMapping("login")//将这个方法映射到/user/login路径上的HTTP请求
    public ResultVo login(@RequestParam("accountNumber") @NotEmpty @NotNull String accountNumber,
                          @RequestParam("userPassword") @NotEmpty @NotNull String userPassword,
                          @RequestParam("captcha") @NotEmpty @NotNull String captcha,
                          HttpServletRequest request, //获取http请求对象
                          HttpServletResponse response) {//设置http响应对象

        String sessionCaptcha = (String) request.getSession().getAttribute("captchaCode");//从会话中获取存储的验证码
        if (!captcha.equalsIgnoreCase(sessionCaptcha)) {//输入的验证码与会话中验证码匹配
            return ResultVo.fail(ErrorMsg.CAPTCHA_ERROR);
        }

        shUser userModel = userService.userLogin(accountNumber, userPassword);
        System.out.println("登录：" + userModel);
        if (null == userModel) {//登录失败
            return ResultVo.fail(ErrorMsg.EMAIL_LOGIN_ERROR);
        }
        if(userModel.getUserStatus()!=null&&userModel.getUserStatus().equals((byte) 0)){//检测用户状态
            return ResultVo.fail(ErrorMsg.ACCOUNT_Ban);
        }
        Cookie cookie = new Cookie("shUserId", String.valueOf(userModel.getId()));//把用户id信息写入cookie
        cookie.setPath("/");//设置 Cookie 的路径为 /，这意味着该 Cookie 对整个应用程序的所有路径都是可见的。
        cookie.setHttpOnly(false);//客户端脚本是否可以访问该 Cookie。true，客户端脚本（JavaScript）将无法访问该 Cookie，
        response.addCookie(cookie);//返回值加入cookie
        return ResultVo.success(userModel);
    }


    /**
     * 退出登录
     *
     * @param shUserId
     * @param response
     * @return
     */
    @RequestMapping("logout")
    public ResultVo logout(@CookieValue("shUserId")
                           @NotNull(message = "登录异常 请重新登录")
                           @NotEmpty(message = "登录异常 请重新登录") String shUserId, HttpServletResponse response) {
        //删除cookie，新写然后覆盖
        Cookie cookie = new Cookie("shUserId", shUserId);
        cookie.setMaxAge(0);//把生命周期设成0
        cookie.setPath("/");
        cookie.setHttpOnly(true);//true，客户端脚本（JavaScript）将无法访问该 Cookie，
        response.addCookie(cookie);//删除的cookie写入响应，返还给客户端浏览器
        return ResultVo.success();
    }

    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("info")
    public ResultVo getOneUser(@CookieValue("shUserId") @NotNull(message = "登录异常 请重新登录")
                               @NotEmpty(message = "登录异常 请重新登录")
                                       String id) {
        return ResultVo.success(userService.getUser(Long.valueOf(id)));
    }

    /**
     * 修改用户公开信息
     * @param id
     * @param userModel
     * @return
     */
    @PostMapping("/info")
    public ResultVo updateUserPublicInfo(@CookieValue("shUserId") @NotNull(message = "登录异常 请重新登录")
                                     @NotEmpty(message = "登录异常 请重新登录")
                                             String id, @RequestBody shUser userModel) {
        userModel.setId(Long.valueOf(id));
        if (userService.updateUserInfo(userModel)) {
            return ResultVo.success();
        }
        return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
    }


    /**
     * 修改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @GetMapping("/password")
    public ResultVo updateUserPassword(@CookieValue("shUserId") @NotNull(message = "登录异常 请重新登录")
                                       @NotEmpty(message = "登录异常 请重新登录") String id,
                                       @RequestParam("oldPassword") @NotEmpty @NotNull String oldPassword,
                                       @RequestParam("newPassword") @NotEmpty @NotNull String newPassword) {
        if (userService.updatePassword(newPassword,oldPassword,Long.valueOf(id))) {
            return ResultVo.success();
        }
        return ResultVo.fail(ErrorMsg.EMAIL_LOGIN_ERROR);
    }

    @GetMapping("/getMoney")
    public ResultVo getMoney(@RequestParam("userId") @NotEmpty @NotNull String id){

        return ResultVo.success(userService.getUser(Long.valueOf(id)));
//        return ResultVo.fail(ErrorMsg.EMAIL_LOGIN_ERROR);
    }

    @PostMapping("/money")
    public ResultVo updateUserMoney(@RequestParam("userId") @NotEmpty @NotNull String id
                                ,@RequestParam("money") @NotEmpty @NotNull String money) {

        if (userService.updateMoney(id,money)) {
            return ResultVo.success();
        }
        return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
    }
}
